package com.srwl.mytx.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.easeui.widget.MyTitleBar;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.BalanceStatementAdapter;
import com.srwl.mytx.adapter.ConsumeSortAdapter;
import com.srwl.mytx.constant.StatementConstant;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Statement;
import com.srwl.mytx.service.StatementService;
import com.srwl.mytx.widget.BottomDialog;
import com.srwl.mytx.widget.ConsumeSortDialog;
import com.srwl.mytx.widget.NodataFooter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 账户余额流水清单
 */
public class BalanceStatementFragment extends Fragment implements BottomDialog.InteractionListener {
    private static final String TAG = "BalanceStatement...";
    private Boolean hasNextPage;

    public static BalanceStatementFragment newInstance() {
        return new BalanceStatementFragment();
    }

    private MaterialSmoothRefreshLayout refreshLayout;
    private RecyclerView rv_statement;
    private ProgressBar progressBar;
    private LinearLayout ll_consumption_type;
    private TextView tv_consumption_types;
    private BalanceStatementAdapter statementAdapter;
    private List<Statement> statementList = new ArrayList<>();
    private int selectItem;  //用于记录被选中的item
    private int page = 1;
    private static final int SIZE = 20;
    private Integer queryType = StatementConstant.STATEMENT_TYPE_ALL;  //用于记录当前查询的type类型

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.statement_fragment, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        refreshLayout = getView().findViewById(R.id.refresh_layout);
        rv_statement = getView().findViewById(R.id.rv_statement);
        progressBar = getView().findViewById(R.id.progress_bar);
        ll_consumption_type = getView().findViewById(R.id.ll_consumption_type);
        tv_consumption_types = getView().findViewById(R.id.tv_consumption_types);
        statementAdapter = new BalanceStatementAdapter(getActivity(), statementList);
        rv_statement.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv_statement.setAdapter(statementAdapter);
        MyTitleBar titleBar = getView().findViewById(R.id.title_bar);
        titleBar.setTitle("余额账单");
        loadData(true, false);
        initEvent();
        initRefreshLayout();
    }


    private void initEvent() {
        ll_consumption_type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> items = new ArrayList<>();
                items.add("全部");
                items.add("充值");
                items.add("提现");
                items.add("捐赠");
                items.add("红包");
                items.add("转账");
                items.add("悬赏");
                items.add("广告");
                items.add("直播");
                ConsumeSortDialog consumeSortDialog = new ConsumeSortDialog(getActivity(), items, selectItem);
                //consumeSortDialog.setCancelable(false);
                consumeSortDialog.setCanceledOnTouchOutside(true);
                consumeSortDialog.show();

                consumeSortDialog.setOnItemClickListener(new ConsumeSortAdapter.OnItemClickListener() {
                    @Override
                    public void onClick(int position, String str) {
                        //展示具体消费类型的逻辑
                        tv_consumption_types.setText(str);
                        switch (position) {
                            case 0:
                                queryType = StatementConstant.STATEMENT_TYPE_ALL;
                                break;
                            case 1:
                                queryType = StatementConstant.STATEMENT_TYPE_RECHARGE;
                                break;
                            case 2:
                                queryType = StatementConstant.STATEMENT_TYPE_TRANSFER;
                                break;
                            case 3:
                                queryType = StatementConstant.STATEMENT_TYPE_DONATION;
                                break;
                            case 4:
                                queryType = StatementConstant.STATEMENT_TYPE_COUPON;
                                break;
                            case 5:
                                queryType = StatementConstant.STATEMENT_TYPE_COIN_TRANSFER;
                                break;
                            case 6:
                                queryType = StatementConstant.STATEMENT_TYPE_REWARD_TASK;
                                break;
                            case 7:
                                queryType = StatementConstant.STATEMENT_TYPE_ADVERTISEMENT_ORDER;
                                break;
                            case 8:
                                queryType = StatementConstant.STATEMENT_TYPE_LIVE;
                                break;
                        }
                        page = 1;
                        loadData(true, true);
                        selectItem = position;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(100l);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                consumeSortDialog.dismiss();
                            }
                        }).start();
                    }
                });
            }
        });


    }


    private void initRefreshLayout() {
        refreshLayout.setDisableRefresh(false);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                page = 1;
                loadData(false, true);
            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage) {
                    loadData(false, false);
                } else {
                    refreshLayout.refreshComplete();
                }
            }
        });
    }

    private void loadData(boolean isFirst, boolean isRefresh) {
        if (!Helper.getInstance().isNetworkConnected()) {
            if (!isFirst) refreshLayout.refreshComplete();
            Toast.makeText(getContext(), getContext().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        if (isFirst) {
            progressBar.setVisibility(View.VISIBLE);
        }
        Map<String, Object> body = new HashMap<>();
        body.put("size", SIZE);
        body.put("page", page);
        body.put("type", queryType);

        RetrofitManager.getInstance().createRequest(StatementService.class)
                .queryBalanceStatement(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            if (page == 1) {
                                statementAdapter.showErrorView();
                            }
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            if (page == 1) {
                                statementAdapter.showErrorView();
                            }
                            return;
                        }
                        Log.d(TAG, "onResponse: 获取清单数据完成");
                        JSONObject pageInfo = (JSONObject) result.getData();
                        hasNextPage = pageInfo.getBoolean("hasNextPage");
                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> {
                                if (getActivity() != null) {
                                    refreshLayout.setFooterView(new NodataFooter(getActivity()));
                                }
                            }, 2000);
                        }
                        List<Statement> statements = pageInfo.getJSONArray("list").toJavaList(Statement.class);
                        if (isRefresh) {
                            statementList.clear();
                        }
                        if (statements.size() > 0) {
                            statementList.addAll(statements);
                            statementAdapter.showNormalView();
                            page++;
                        } else {
                            statementAdapter.showNoDataView();
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        if (page == 1) {
                            statementAdapter.showErrorView();
                        }
                        t.printStackTrace();
                    }
                });
    }


    @Override
    public void onDialogItemViewClick(int position, String itemName) {

    }
}
